﻿using System;
using System.Data.SqlClient;
using Company.BLL.WS.KDT.SXXK;
using Company.BLL.WS.KDT.GC;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace Company.BLL.KDT.GC
{
    public partial class ToKhaiChuyenTiep
    {
        private HangChuyenTiepCollection _HCTCollection = new HangChuyenTiepCollection();

        public HangChuyenTiepCollection HCTCollection
        {
            set { this._HCTCollection = value; }
            get { return this._HCTCollection; }
        }

        //-----------------------------------------------------------------------------------------

        public ToKhaiChuyenTiepInfo ExportToInfo()
        {
            ToKhaiChuyenTiepInfo webTKCTInfo = new ToKhaiChuyenTiepInfo();
            webTKCTInfo.So_TNDKDT = this.SoTiepNhan;
            webTKCTInfo.Nam_TN = Convert.ToInt16(this.NgayTiepNhan.Year);
            webTKCTInfo.Ma_HQTN = this.MaHQ;
            webTKCTInfo.DVGC = this.MaNguoiNhan;
            webTKCTInfo.Ma_CT = this.MaLoaiHinh;
            webTKCTInfo.Ngay_CT = this.NgayDangKy;
            webTKCTInfo.Nam_CT = Convert.ToInt16(this.NgayDangKy.Year);
            webTKCTInfo.DVGC = this.MaNguoiNhan;
            webTKCTInfo.So_CT = Convert.ToInt16(this.ToKhaiSo);
            webTKCTInfo.Ma_DoiTac = this.MaNguoiGiao;
            webTKCTInfo.DoiTac = this.TenNguoiGiao;
            webTKCTInfo.Ma_HQ = this.MaHQ;
            webTKCTInfo.So_HD = this.SoHopDongNhan;
            webTKCTInfo.Ngay_Ky = this.NgayHDNhan;
            webTKCTInfo.Ngay_HH = this.NgayHetHanHDNhan;
            webTKCTInfo.So_HDCh = this.SoHDGiao;
            webTKCTInfo.Ngay_KyCh = this.NgayHDGiao;
            webTKCTInfo.Ngay_HHCh = this.NgayHetHanHDGiao;
            webTKCTInfo.NguoiGiao = this.TenNguoiNhan;
            webTKCTInfo.NgayGiao = DateTime.Today;
            webTKCTInfo.NguoiNhan = this.TenNguoiGiao;
            webTKCTInfo.NgayNhan = DateTime.Today;
            webTKCTInfo.Ma_HQKH = this.MaHQ;
            webTKCTInfo.NguoiHQGiao = this.NguoiChiDinhGiaoHang;
            webTKCTInfo.NgayHQGiao = DateTime.Today;
            webTKCTInfo.NguoiHQNhan = this.DiaDiemXepHang;
            webTKCTInfo.NgayHQNhan = DateTime.Today;
            webTKCTInfo.Ma_NT = this.MaNguyenTe;
            webTKCTInfo.CTKT = this.ChungTu;
            webTKCTInfo.TyGiaVND = this.TyGiaVND;
            webTKCTInfo.LePhiHQ = this.LePhiHQ;
            webTKCTInfo.TrangThaiXL = this.TrangThai;
            webTKCTInfo.MaDVKB = this.MaNguoiNhan;
            webTKCTInfo.UserKH1 = this.MaDaiLy;
            webTKCTInfo.UserKH2 = this.TenDaiLy;
            webTKCTInfo.UserTH = this.SoBienLai;
            webTKCTInfo.NgayTH = this.NgayBienLai;
            return webTKCTInfo;
        }
        public void LoadHCTCollection()
        {
            HangChuyenTiep hct = new HangChuyenTiep();
            hct.Master_ID = this.ID;
            this.HCTCollection = hct.SelectCollectionBy_Master_ID();
        }

        //-----------------------------------------------------------------------------------------

        public long InsertFull()
        {
            long ret;
            using (SqlConnection connection = (SqlConnection) db.CreateConnection())
            {
                connection.Open();
                SqlTransaction transaction = connection.BeginTransaction();
                try
                {
                    long ret01 = this.InsertTransaction(transaction);
                    foreach (HangChuyenTiep hct in this.HCTCollection)
                    {
                        hct.Master_ID = ret01;
                        hct.InsertTransaction(transaction);
                    }
                    if (ret01 > 0)
                    {
                        transaction.Commit();
                        ret = ret01;
                    }
                    else
                    {
                        transaction.Rollback();
                        ret = 0;
                    }
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw new Exception(ex.Message);
                }
                finally
                {
                    connection.Close();
                }
            }
            return ret;
        }
        public long UpdateFull()
        {
            long ret;
            using (SqlConnection connection = (SqlConnection)db.CreateConnection())
            {
                connection.Open();
                SqlTransaction transaction = connection.BeginTransaction();
                try
                {
                    long ret01 = this.UpdateTransaction(transaction);
                    foreach (HangChuyenTiep hct in this.HCTCollection)
                    {
                        if (hct.Load()) hct.UpdateTransaction(transaction);
                        else
                        {
                            hct.Master_ID = this.ID;                          
                            hct.InsertTransaction(transaction);
                        }
                    }
                    if (ret01 > 0)
                    {
                        transaction.Commit();
                        ret = ret01;
                    }
                    else
                    {
                        transaction.Rollback();
                        ret = 0;
                    }
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw new Exception(ex.Message);
                }
                finally
                {
                    connection.Close();
                }
            }
            return ret;
        }

        private void InsertUpdateFull(SqlTransaction transaction)
        {
            if (this.ID == 0)
                this.ID = this.InsertTransaction(transaction);
            else
                this.UpdateTransaction(transaction);

            foreach (HangChuyenTiep hctDetail in this.HCTCollection)
            {
                if (hctDetail.ID == 0)
                {
                    hctDetail.Master_ID = this.ID;
                    hctDetail.ID = hctDetail.InsertTransaction(transaction);
                }
                else
                {
                    hctDetail.UpdateTransaction(transaction);
                }
            }
        }
        private bool InsertUpdateFull()
        {
            bool ret;
            SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
            using (SqlConnection connection = (SqlConnection)db.CreateConnection())
            {
                connection.Open();
                SqlTransaction transaction = connection.BeginTransaction();
                try
                {
                    if (this.ID == 0)
                        this.ID = this.InsertTransaction(transaction);
                    else
                        this.UpdateTransaction(transaction);

                    foreach (HangChuyenTiep hct in this.HCTCollection)
                    {
                        if (hct.ID == 0)
                        {
                            hct.Master_ID = this.ID;
                            hct.ID = hct.InsertTransaction(transaction);
                        }
                        else
                        {
                            hct.UpdateTransaction(transaction);
                        }
                    }
                    transaction.Commit();
                    ret = true;
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw new Exception(ex.Message);
                }
                finally
                {
                    connection.Close();
                }
            }
            return ret;
        }
        #region Web Services

        //-----------------------------------------------------------------------------------------
        public long WSSend()
        {
            // Chuẩn bị dữ liệu để gửi qua WEB SERVICE.
            // Lấy thông tin đăng ký.
            KDT_GC_Service kdtService = new KDT_GC_Service();
            ToKhaiChuyenTiepInfo webTKCTInfo = this.ExportToInfo(); 
            // Lấy danh sách hàng hóa.
            int count = this.HCTCollection.Count;
            webTKCTInfo.HangCTInfoCollection = new HangChuyenTiepInfo[count];
            int i = 0;
            foreach (HangChuyenTiep hctDetail in this.HCTCollection)
            {
                HangChuyenTiepInfo webHCTInfo = new HangChuyenTiepInfo();
                webHCTInfo.MaHQTN = this.MaHQ;
                webHCTInfo.MaChungTu = this.MaLoaiHinh;
                webHCTInfo.SoChungTu = Convert.ToInt16(this.ToKhaiSo);
                webHCTInfo.NamChungTu = Convert.ToInt16(this.NgayDangKy.Year);
                webHCTInfo.NgayChungTu = this.NgayDangKy;
                webHCTInfo.MaHS = hctDetail.MaHS;
                webHCTInfo.MaHang = hctDetail.MaHang;
                webHCTInfo.TenHang = hctDetail.TenHang;
                webHCTInfo.ID_DVT = hctDetail.ID_DVT;
                webHCTInfo.ID_NuocXX = hctDetail.ID_NuocXX;
                webHCTInfo.SoLuong = hctDetail.SoLuong;
                webHCTInfo.DonGia = hctDetail.DonGia;
                webHCTInfo.TriGia = hctDetail.TriGia;
                webHCTInfo.MaHQ = this.MaHQ;
                webHCTInfo.STTHang = hctDetail.SoThuTuHang;
                webTKCTInfo.HangCTInfoCollection[i] = webHCTInfo;
                i++;
            }

            // Thực hiện gửi dữ liệu.

            this.SoTiepNhan = kdtService.ToKhaiChuyenTiep_Send(webTKCTInfo);
            if (this.SoTiepNhan > 0)
            {
                this.TrangThai = BLL.TrangThaiXuLy.CHO_DUYET;
                this.NgayTiepNhan = DateTime.Today;
                
            }
            this.InsertUpdateFull();
            return this._SoTiepNhan;
        }





        //-----------------------------------------------------------------------------------------
        /// <summary>
        /// Hủy thông tin khai báo.
        /// </summary>
        public bool WSCancel()
        {
            bool result = false;
            KDT_GC_Service kdtService = new KDT_GC_Service();
            result = kdtService.ToKhaiChuyenTiep_Cancel(this.SoTiepNhan, this.MaHQ, this.MaNguoiNhan, this.NgayTiepNhan.Year);
            if (result)
            {
                // Trả lại trạng thái chưa khai báo.
                this.SoTiepNhan = 0;
                this.NgayTiepNhan = new DateTime(1900, 1, 1);
                this.TrangThai = BLL.TrangThaiXuLy.CHUA_KHAI_BAO;
                this.Update();
            }
            return result;
        }

        //-----------------------------------------------------------------------------------------
        public void WSRequestStatus()
        {
            // Các bước thực hiện:
            // 1. Lấy thông tin từ Web Service.
            // 2. Cập nhật thông tin đăng ký.
            // 3. Xóa danh sách hàng chuyển tiếp cũ.
            // 4. Cập nhật lại danh sách hàng chuyển tiếp mới mới.
            // 5. Nếu trạng thái: Đã duyệt chính thức thì chuyển danh sách sản phẩm đã duyệt sang phân hệ SXXK.

            // 1. Lấy danh sách từ Web Service.
            KDT_GC_Service kdtService = new KDT_GC_Service();
            DataSet ds = kdtService.ToKhaiChuyenTiep_RequestStatus(this.SoTiepNhan, this.MaHQ, this.MaNguoiNhan, Convert.ToInt16(this.NgayTiepNhan.Year));
            DataTable dt = ds.Tables[0];
            if (dt.Rows.Count > 0)
            {
                SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
                using (SqlConnection connection = (SqlConnection)db.CreateConnection())
                {
                    connection.Open();
                    SqlTransaction transaction = connection.BeginTransaction();
                    try
                    {
                        // 2. Cập nhật thông tin đăng ký.
                        this.TrangThai = Convert.ToInt32(dt.Rows[0]["TrangThaiXL"]);
                        this.MaLoaiHinh = Convert.ToString(dt.Rows[0]["Ma_CT"]);
                        if (dt.Rows[0]["So_CT"].ToString()!="")
                            this.ToKhaiSo = Convert.ToInt32(dt.Rows[0]["So_CT"].ToString());
                        this.CanBoDangKy = Convert.ToString(dt.Rows[0]["Nguoi_VM"]);
                        if (dt.Rows[0]["Ngay_VM"].ToString() != "")
                            this.NgayDangKy = Convert.ToDateTime(dt.Rows[0]["Ngay_VM"].ToString());
                        this.SoHopDongNhan = Convert.ToString(dt.Rows[0]["So_HD"]);
                        this.MaNguoiNhan = Convert.ToString(dt.Rows[0]["DVGC"]);
                        this.TenNguoiNhan = Convert.ToString(dt.Rows[0]["NguoiGiao"]);
                        if (dt.Rows[0]["Ngay_Ky"].ToString() != "")
                            this.NgayHDNhan = Convert.ToDateTime(dt.Rows[0]["Ngay_Ky"]);
                        if (dt.Rows[0]["Ngay_HH"].ToString() != "")
                            this.NgayHetHanHDNhan = Convert.ToDateTime(dt.Rows[0]["Ngay_HH"]);
                        this.MaNguoiGiao = Convert.ToString(dt.Rows[0]["Ma_DoiTac"]);
                        this.TenNguoiGiao = Convert.ToString(dt.Rows[0]["DoiTac"]);
                        this.SoHDGiao = Convert.ToString(dt.Rows[0]["so_HDCh"]);
                        if (dt.Rows[0]["Ngay_KyCh"].ToString() != "")
                            this.NgayHDGiao= Convert.ToDateTime(dt.Rows[0]["Ngay_KyCh"]);
                        if (dt.Rows[0]["Ngay_HHCh"].ToString() != "")
                            this.NgayHetHanHDGiao = Convert.ToDateTime(dt.Rows[0]["Ngay_HHCh"]);
                        this.NguoiChiDinhGiaoHang = Convert.ToString(dt.Rows[0]["NguoiHQGiao"]);
                        this.MaDaiLy = Convert.ToString(dt.Rows[0]["UserKH1"]);
                        this.TenDaiLy = Convert.ToString(dt.Rows[0]["UserKH2"]);
                        this.DiaDiemXepHang = Convert.ToString(dt.Rows[0]["NguoiHQNhan"]);
                        if (dt.Rows[0]["TyGiaVND"].ToString() != "")
                            this.TyGiaVND = Convert.ToDecimal(dt.Rows[0]["TyGiaVND"].ToString());
                        if (dt.Rows[0]["LePhiHQ"].ToString() != "")
                            this.LePhiHQ = Convert.ToDecimal(dt.Rows[0]["LePhiHQ"]);
                        this.SoBienLai = Convert.ToString(dt.Rows[0]["UserTH"]);
                        if (dt.Rows[0]["NgayTH"].ToString() != "")
                            this.NgayBienLai = Convert.ToDateTime(dt.Rows[0]["NgayTH"]);
                        this.ChungTu = Convert.ToString(dt.Rows[0]["CTKT"]);
                        this.MaNguyenTe = Convert.ToString(dt.Rows[0]["Ma_NT"]);


                        // 3. Xóa danh sách hàng chuyển tiếp cũ.
                        this.LoadHCTCollection();
                        new HangChuyenTiep().DeleteCollection(this.HCTCollection, transaction);
                        this.HCTCollection.Clear();

                        // 4. Cập nhật lại danh sách hàng chuyển tiếp mới.
                        int stt = 1;
                        foreach (DataRow row in dt.Rows)
                        {
                            HangChuyenTiep hct = new HangChuyenTiep();
                            hct.Master_ID = this.ID;
                            hct.MaHang = row["P_Code"].ToString();
                            hct.TenHang = row["TenHang"].ToString();
                            hct.MaHS = row["HS_Code"].ToString();
                            hct.ID_DVT = row["Ma_DVT"].ToString();
                            hct.ID_NuocXX = row["NuocXX"].ToString();
                            hct.SoLuong = Convert.ToDecimal(row["SoLuong"].ToString());
                            hct.DonGia = Convert.ToDecimal(row["DonGia"].ToString());
                            hct.TriGia = Convert.ToDecimal(row["TriGia"].ToString());
                            hct.SoThuTuHang = stt++;
                            this.HCTCollection.Add(hct);
                        }

                        // Cập nhật vào CSDL.
                        this.InsertUpdateFull(transaction);

                        // 5. Nếu trạng thái là đã duyệt chính thức thì chuyển danh sách sản phẩm đã duyệt sang phân hệ SXXK.
                        if (this.TrangThai == BLL.TrangThaiXuLy.DA_DUYET)
                        {
                            //foreach (DataRow row in dt.Rows)
                            //{
                            //    BLL.SXXK.SanPham sp = new BLL.SXXK.SanPham();
                            //    sp.MaHaiQuan = this._MaHaiQuan;
                            //    sp.MaDoanhNghiep = this._MaDoanhNghiep;
                            //    sp.Ma = row["Ma_SP"].ToString();
                            //    sp.Ten = row["Ten_SP"].ToString();
                            //    sp.MaHS = row["Ma_HS"].ToString();
                            //    sp.DVT_ID = row["Ma_DVT"].ToString();

                            //    sp.InsertUpdateTransaction(transaction);
                            //}
                        }

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
            else
            {
                this.Update();
            }
        }



        #endregion
    }
}